#include "widget.h"
#include "./ui_widget.h"

#include <QFileDialog>
#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    //设置程序图片及名称
    setWindowIcon(QIcon(":/resource/icon.png"));
    this->setWindowTitle("Music Player");
    //设置无边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->setupUi(this);

    QDir::setCurrent(QCoreApplication::applicationDirPath());
    QDir dir;
    if(!dir.exists("Album")){
        dir.mkdir("Album");
    }
    player = new QMediaPlayer;

    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), this, SLOT(onMediaStatusChanged(QMediaPlayer::MediaStatus)));

    playslider_timer = new QTimer(this);
    playslider_timer->setInterval(1000);
    connect(playslider_timer, SIGNAL(timeout()), this, SLOT(setPlaySliderValue()));

    musiclist_menu = new QMenu(this);
    action_delete_musiclist = new QAction(tr("删除该歌单"), this);
    action_play_musiclist = new QAction(tr("播放该歌单"), this);
    musiclist_menu->addAction(action_delete_musiclist);
    musiclist_menu->addAction(action_play_musiclist);

    ui->musiclist_listWidget->setProperty("contextMenuPolicy", Qt::CustomContextMenu);

    connect(action_delete_musiclist, SIGNAL(triggered()), this, SLOT(onActionDeleteMusiclist()));
    connect(action_play_musiclist, SIGNAL(triggered()), this, SLOT(onActionPlayMusiclist()));

    ui->music_list_table->setSelectionBehavior (QAbstractItemView::SelectRows); //设置选择行为，以行为单位
    ui->music_list_table->setSelectionMode (QAbstractItemView::SingleSelection); //设置选择模式，选择单行
    ui->music_list_table->verticalHeader()->setHidden(true);
    ui->music_list_table->setShowGrid(false);
    ui->music_list_table->setAlternatingRowColors(true);
    ui->music_list_table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    ui->music_list_table->setColumnWidth(0, 500);
    ui->music_list_table->setColumnWidth(1, 200);
    ui->music_list_table->setColumnWidth(2, 200);
    ui->music_list_table->horizontalHeader()->setStretchLastSection(true);

    connect(ui->musiclist_listWidget, &QListWidget::itemClicked, this, &Widget::onShowMusiclistClicked);
    connect(ui->add_music, &QPushButton::clicked, this, &Widget::onAddMusiclistClicked);
    connect(ui->close_btn, &QPushButton::clicked, this, &Widget::onClose);
    connect(ui->min_btn, &QPushButton::clicked, this,&Widget::onWindowMin);
    connect(ui->add_song, &QPushButton::clicked, this, &Widget::onOpenFolder);

    connect(ui->musiclist_listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onShowMusicListMenu(QPoint)));

    song_menu = new QMenu(this);
    QAction *play_action = new QAction("播放", this);
    QAction *delete_action = new QAction("删除", this);

    song_menu->addAction(play_action);
    song_menu->addAction(delete_action);
    show_musiclist_menu = song_menu->addMenu("收藏到歌单");

    ui->music_list_table->setProperty("contextMenuPolicy", Qt::CustomContextMenu);
    connect(ui->music_list_table, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onShowSongMenu(QPoint)));
    connect(ui->music_list_table, &QTableWidget::itemDoubleClicked, this, &Widget::onActionPlay);

    isSliderMoved = false;
    isSliderPressed = false;

    ui->play_ctl_slider->setMaximum(1000);
    ui->voice_ctl_slider->setMaximum(100);

    connect(ui->play_btn, &QPushButton::clicked, this, &Widget::onPlay);
    connect(ui->pre_btn, &QPushButton::clicked, this, &Widget::onPre);
    connect(ui->play_ctl_slider, &QSlider::sliderMoved, this, &Widget::onSliderMoved);
    connect(ui->play_ctl_slider, &QSlider::sliderReleased, this, &Widget::onSliderReleased);
    connect(ui->play_ctl_slider, &QSlider::sliderPressed, this, &Widget::onSliderPressed);
    connect(ui->voice_ctl_slider, &QSlider::valueChanged, this, &Widget::setVoiceSliderValue);
    connect(ui->next_btn, &QPushButton::clicked, this, &Widget::onNext);

    ui->voice_ctl_slider->setValue(40);
    player->setVolume(40);

    connect(play_action, SIGNAL(triggered()), this, SLOT(onActionPlay()));
    connect(delete_action, SIGNAL(triggered()), this, SLOT(onActionDeleteSong()));

    //歌词面板相关
    ui->lyrics_widget->hide();
    cur_lyrics_line = 0;

    lyrics_timer = new QTimer(this);
    lyrics_timer->setSingleShot(true);

    font_normal.setFamily("微软雅黑");
    font_normal.setPointSize(11);

    font_bold.setFamily("微软雅黑");
    font_bold.setPointSize(13);
    font_bold.setBold(true);

    qDebug() << ui->gridLayout->rowCount() << ui->gridLayout->columnCount();
    ui->lyrics_listwidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);

    connect(ui->album, &QPushButton::clicked, this, &Widget::showLyricWidget);
    connect(lyrics_timer, SIGNAL(timeout()), this, SLOT(showNextLyrics()));

    //播放列表相关
    ui->playlist_tabel->setEditTriggers(QAbstractItemView::NoEditTriggers);   //禁止编辑
    ui->playlist_tabel->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->playlist_tabel->verticalHeader()->setVisible(false); //隐藏行表头
    ui->playlist_tabel->horizontalHeader()->setVisible(false);
    ui->playlist_tabel->setShowGrid(false);                    //不显示表格线
    ui->playlist_tabel->setSelectionMode(QAbstractItemView::SingleSelection);//只能单选
    ui->playlist_tabel->setAlternatingRowColors(true);

    ui->playlist_tabel->horizontalHeader()->setStretchLastSection(true);

    playlist = new PlayList(PlayList::OrderPlay);  //默认顺序播放
    ui->playlist_widget->hide();
    connect(ui->playlist_btn, &QPushButton::clicked, this, &Widget::showPlaylistWidget);
    connect(ui->playmode_btn, &QPushButton::clicked, this, &Widget::onChangePlayMode);

    initUI();

    //数据库相关
    if(!Connection::createConnection())
    {
        qDebug() << "数据库初始化失败。";
        close();
    }

    m_playlists = Connection::getMusicLists();
    ListNode<MusicList*>* tmp_node = m_playlists->start();

    while(tmp_node != NULL)
    {
        QListWidgetItem* tmp_item = new LWI_MusicListItem(tmp_node->data, QIcon(":/resource/musiclist.svg"));
        tmp_item->setText(tmp_node->data->musiclist_name);
        ui->musiclist_listWidget->addItem(tmp_item);
        tmp_node = tmp_node->next;
    }
    cur_music_list = NULL;
}

Widget::~Widget()
{
    delete ui;
}

//显示选中歌单内容
void Widget::onShowMusiclistClicked()
{
    if(cur_music_list != NULL && !m_playlists->findNode(cur_music_list))
    {
        delete cur_music_list;
    }

    QList<QListWidgetItem *> tmp_list = ui->musiclist_listWidget->selectedItems();

    MusicList* tmp_ml = ((LWI_MusicListItem*)tmp_list[0])->getMusicList();

    //显示的歌单未变化
    if(cur_music_list == tmp_ml)
        return;

    //从数据库获取歌单的歌曲
    if(!tmp_ml->isFlush)
    {
         tmp_ml->clear();
        if(!Connection::getSongsFromMusicList(tmp_ml))
        {
            qDebug() << "获取歌单的歌曲失败。";
            return;
        }
    }

    //添加到显示列表上
    ui->music_list_table->clearContents();

    tmp_ml->goStart();
    ui->music_list_table->setRowCount(tmp_ml->getSongCnt());  

    for(int i = 0; i < tmp_ml->getSongCnt(); ++i)
    {
         Song* tmp_song = tmp_ml->next();
         QTableWidgetItem *item1 = new QTableWidgetItem (tmp_song->Name.size() > 0? tmp_song->Name : tmp_song->File_name);
         item1->setData(Qt::UserRole, QVariant::fromValue(tmp_song));
         ui->music_list_table->setItem(i, 0, item1);

         QTableWidgetItem *item2 = new QTableWidgetItem (tmp_song->Singer);
         ui->music_list_table->setItem(i, 1, item2);

         QTableWidgetItem *item3 = new QTableWidgetItem (tmp_song->Album);
         ui->music_list_table->setItem(i, 2, item3);

         QTableWidgetItem *item4 = new QTableWidgetItem (tmp_song->Time? getTime2Str(tmp_song->Time) : 0);
         ui->music_list_table->setItem(i, 3, item4);
    }

    cur_music_list = tmp_ml;
}

//显示歌单内容
void Widget::showMusiclist(MusicList* ml)
{
    ui->music_list_table->clearContents();
    ml->goStart();

    ui->music_list_table->setRowCount(ml->getSongCnt());

    for(int i = 0; i < ml->getSongCnt(); ++i)
    {
         Song* tmp_song = ml->next();
         qDebug() << "name length: " << tmp_song->Name.size();
         qDebug() << "File name: " << tmp_song->File_name;
         QTableWidgetItem *item1 = new QTableWidgetItem (tmp_song->Name.size() > 0? tmp_song->Name : tmp_song->File_name);
         item1->setData(Qt::UserRole, QVariant::fromValue(tmp_song));
         ui->music_list_table->setItem(i, 0, item1);

         QTableWidgetItem *item2 = new QTableWidgetItem (tmp_song->Singer);
         ui->music_list_table->setItem(i, 1, item2);

         QTableWidgetItem *item3 = new QTableWidgetItem (tmp_song->Album);
         ui->music_list_table->setItem(i, 2, item3);

         QTableWidgetItem *item4 = new QTableWidgetItem (tmp_song->Time? getTime2Str(tmp_song->Time) : 0);
         ui->music_list_table->setItem(i, 3, item4);
    }

    cur_music_list = ml;
}

//添加歌单
void Widget::onAddMusiclistClicked()
{
    bool bOk = false;
    QString sName = QInputDialog::getText(this,
                                             "QInputdialog_Name",
                                             "新建歌单",
                                             QLineEdit::Normal,
                                             "歌单名字",
                                             &bOk
                                             );

    if (bOk && !sName.isEmpty())
    {
        MusicList* tmp = new MusicList;
        tmp->musiclist_name = sName;

        if(Connection::addMusicList(tmp))
        {
            m_playlists->addNode(tmp);
            QListWidgetItem* tmp_item = new LWI_MusicListItem(tmp, QIcon(":/resource/musiclist.svg"));
            tmp_item->setText(sName);
            ui->musiclist_listWidget->addItem(tmp_item);
        }
    }
}


//关闭程序
void Widget::onClose()
{
    QApplication* app;
    app->quit();
}

//最小化窗口
void Widget::onWindowMin()
{
    this->showMinimized();
}

//删除歌单
void Widget::onActionDeleteMusiclist()
{
    /*获取当前选中的Item*/
    QList<QListWidgetItem*> items = ui->musiclist_listWidget->selectedItems();

    if (items.count() > 0)
    {
        /*弹出询问对话框*/
        if (QMessageBox::Yes == QMessageBox::question(this, "删除歌单",
                                                      "删除该歌单？", QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
        {
            foreach(QListWidgetItem* var, items) {
                LWI_MusicListItem* tmp = (LWI_MusicListItem*) var;
                MusicList* tmp_ml = tmp->getMusicList();

                if(Connection::deleteMusicList(tmp_ml))
                {
                    ui->musiclist_listWidget->removeItemWidget(var);
                    items.removeOne(var);
                    delete var;

                    if(cur_music_list == tmp_ml)
                    {
                        ui->music_list_table->clearContents();
                        cur_music_list = NULL;
                    }


                    m_playlists->deleteNode(tmp_ml);
                    //delete tmp_ml;
                }
            }
        }
    }
}

//播放歌单
void Widget::onActionPlayMusiclist()
{
    /*获取当前选中的Item*/
    QList<QListWidgetItem*> items = ui->musiclist_listWidget->selectedItems();

    if (items.count() > 0)
    {
        LWI_MusicListItem* tmp = (LWI_MusicListItem*) items[0];
        MusicList* tmp_ml = tmp->getMusicList();

        addPlaylist(tmp_ml);
        Song* s = playlist->playNext();

        playSong(s);
    }
}

//收藏菜单项的响应函数
void Widget::onActionCollect()
{
    int cur_row = ui->music_list_table->currentRow();
    // qDebug() << cur_row;

    if (cur_row >= 0)
    {
        QAction *action = (QAction*)sender();
        QVariant act_var = action->data();
        MusicList *ml = act_var.value<MusicList*>();
        qDebug() << ml->musiclist_name;

        QTableWidgetItem* item = ui->music_list_table->item(cur_row, 0);
        QVariant variant = item->data(Qt::UserRole); // 获取用户数据
        Song* song = variant.value<Song*>();
        qDebug() << song->Name << song->Singer;

        if(Connection::collectSong(song, ml))
            ml->addSong(song);
    }
}

//播放该歌曲菜单项的响应函数
void Widget::onActionPlay()
{
    int cur_row = ui->music_list_table->currentRow();
    // qDebug() << cur_row;

    if (cur_row >= 0)
    {
//        QTableWidgetItem* item = ui->music_list_table->item(cur_row, 0);
//        QVariant variant = item->data(Qt::UserRole); // 获取用户数据
//        Song* song = variant.value<Song*>();
//        cur_music_list->setCurSong(song);
//        playSong(song);

        player->stop();
        QTableWidgetItem* item = ui->music_list_table->item(cur_row, 0);
        QVariant variant = item->data(Qt::UserRole); // 获取用户数据
        Song* song = variant.value<Song*>();

        ui->playlist_widget->hide();
        addPlaylist(cur_music_list);
        Song* s = playlist_hash[song];
        playlist->setCurSong(s);

        playSong(s);
    }
}

//从当前歌单删除歌曲
void Widget::onActionDeleteSong()
{
    int cur_row = ui->music_list_table->currentRow();
    // qDebug() << cur_row;

    if (cur_row >= 0)
    {
        QTableWidgetItem* item = ui->music_list_table->item(cur_row, 0);
        QVariant variant = item->data(Qt::UserRole); // 获取用户数据
        Song* song = variant.value<Song*>();
        qDebug() << song->Name << song->Singer;

        if(Connection::deleteSongFromMusicList(cur_music_list, song))
        {
            cur_music_list->deleteSong(song);
            ui->music_list_table->removeRow(cur_row);
        }
    }
}

//下一首播放菜单项的响应函数,有问题，暂时不用
void Widget::onActionNextPlay()
{
    int cur_row = ui->music_list_table->currentRow();
    // qDebug() << cur_row;

    if (cur_row >= 0)
    {
        Song* tmp_song;
        QTableWidgetItem* item = ui->music_list_table->item(cur_row, 0);
        QVariant variant = item->data(Qt::UserRole); // 获取用户数据
        Song* song = variant.value<Song*>();
        qDebug() << "下一首播放：" << song->Name << song->Singer;


        if(playlist_hash.find(song) == playlist_hash.end())
        {
            tmp_song = song->copy();
            playlist_hash[song] = tmp_song;
            playlist->addNextSong(tmp_song, true);
        }
        else
        {
            tmp_song = playlist_hash[song];
            playlist->addNextSong(tmp_song, false);
        }
    }
}

//显示歌单项右键菜单
void Widget::onShowMusicListMenu(QPoint pos)
{
    /*弹出右键菜单*/
    musiclist_menu->exec(QCursor::pos());
}

//显示歌曲项右键菜单，主要查询当前有哪些歌单
void Widget::onShowSongMenu(QPoint pos)
{
    show_musiclist_menu->clear();
    ListNode<MusicList*>* tmp_node = m_playlists->start();

    while(tmp_node != NULL)
    {
        QAction *tmp = new QAction(tmp_node->data->musiclist_name, this);
        tmp->setData(QVariant::fromValue(tmp_node->data));
        connect(tmp, SIGNAL(triggered()), this, SLOT(onActionCollect()));
        show_musiclist_menu->addAction(tmp);

        tmp_node = tmp_node->next;
    }

    song_menu->exec(QCursor::pos());
}

//打开文件夹添加本地歌曲
void Widget::onOpenFolder()
{
    QString fileName = QFileDialog::getExistingDirectory(NULL, "选择文件夹，仅读取当前文件夹下的MP3文件", ".", NULL);
    QDir dir(fileName);
    QStringList nameFilters;
    nameFilters << "*.mp3";
    QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);


    MP3File mp3;
    MusicList* tmp_ml = new MusicList;;

    for(QString& file : files)
    {
        QString file_path = fileName + '/' + file;
        Song* s = mp3.GetAllInfo(file_path.toStdWString().c_str(), 0);
        tmp_ml->addSong(s);
    }
    cur_music_list = tmp_ml;
    showMusiclist(tmp_ml);
}

void Widget::onPlay()
{
    if(QMediaPlayer::PlayingState == player->state())
    {
        player->pause();
        ui->play_btn->setIcon(QIcon(":/resource/play.svg"));
        lyrics_timer->stop();
    }
    else if(QMediaPlayer::PausedState == player->state())
    {
        player->play();
        ui->play_btn->setIcon(QIcon(":/resource/pause.svg"));
        //无歌词不用启动定时器
        if(lyrics_info.size > 0)
            lyrics_timer->start(lyrics_info.list_lyrics_time[cur_lyrics_line] - player->position());
    }

}

void Widget::onPre()
{
//    Song* song = cur_music_list->pre();
//    if(song != nullptr)
//    {
//       playSong(song);
//    }

    if(playlist->getSize() > 0)
    {
        Song* s = playlist->playPre();
        if(s)
            playSong(s);
        else
            qDebug() << "前一首为空";
    }
}

void Widget::onNext()
{
//    Song* song = cur_music_list->next();
//    if(song != nullptr)
//    {
//        playSong(song);
//    }

    if(playlist->getSize() > 0)
    {
        Song* s = playlist->playNext();
        if(s)
            playSong(s);
        else
            qDebug() << "后一首为空";
    }
}

void Widget::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    qDebug() << "当前状态：" << status;

    if(QMediaPlayer::EndOfMedia == status)
    {
        qDebug() << "当前状态：结束";
        if(playlist->getSize() > 0)
        {
            Song* s = playlist->play();
            if(s != nullptr)
            {
                playSong(s);
            }
            else
                ui->play_btn->setIcon(QIcon(":/resource/play.svg"));
        }

    }
    else if(QMediaPlayer::BufferedMedia == status)
    {
        qDebug() << "歌曲总时间：" << player->duration();
        ui->total_music_time->setText(getTime2Str(player->duration()));
    }
}

void Widget::onChangePlayMode()
{
    PlayList::PlayMode mode = playlist->getPlayMode();
    switch(mode)
    {
        case(PlayList::OrderPlay):
            ui->playmode_btn->setIcon(QIcon(":/resource/singleplay.svg"));
            playlist->setPlayMode(PlayList::SinglePlay);
            ui->playmode_btn->setToolTip("单曲循环");
            ui->playmode_label->setText("单曲循环");
            break;
        case(PlayList::SinglePlay):
            ui->playmode_btn->setIcon(QIcon(":/resource/loopplay.svg"));
            playlist->setPlayMode(PlayList::LoopPlay);
            ui->playmode_btn->setToolTip("循环播放");
            ui->playmode_label->setText("循环播放");
            break;
        case(PlayList::LoopPlay):
            ui->playmode_btn->setIcon(QIcon(":/resource/randomplay.svg"));
            playlist->setPlayMode(PlayList::RandomPlay);
            ui->playmode_btn->setToolTip("随机播放");
            ui->playmode_label->setText("随机播放");
            break;
        case(PlayList::RandomPlay):
            ui->playmode_btn->setIcon(QIcon(":/resource/orderplay.svg"));
            playlist->setPlayMode(PlayList::OrderPlay);
            ui->playmode_btn->setToolTip("顺序播放");
            ui->playmode_label->setText("顺序播放");
            break;
        default:
            break;
    }
}

//释放进度条滑块时的响应函数
void Widget::onSliderReleased()
{
    qDebug() << "release" << player->duration();
    if(player->duration() == 0)
    {
        ui->play_ctl_slider->setValue(0);
        return;
    }

    int time = player->duration()*ui->play_ctl_slider->value()/1000;

    setLyricsPos(time);
    player->setPosition(time);
    setPlayTime(time);

    if(QMediaPlayer::PlayingState == player->state())
        playslider_timer->start();

    isSliderMoved = false;
}

//点击进度条滑块时的响应函数
void Widget::onSliderPressed()
{
    qDebug() << "onSliderPressed";
    isSliderMoved = true;
    playslider_timer->stop();
}

//滑动进度条滑块时的响应函数
void Widget::onSliderMoved(int position)
{
    //qDebug() << "move";
    int time = player->duration()*position/1000;
    setPlayTime(time);
}

//进度条定时器的执行函数
void Widget::setPlaySliderValue()
{
    if(player->duration() > 0 && !isSliderPressed)
    {
        ui->play_ctl_slider->setValue(player->position()*1000/player->duration());
        setPlayTime();
    }
}

//拖动音量条
void Widget::setVoiceSliderValue(int position)
{
    player->setVolume(position);
}

// 双击音乐列表item
//void Widget::itemDoubleClicked(QTableWidgetItem *item)
//{
//    QList<QTableWidgetItem*> items = ui->music_list_table->selectedItems();

//    if(items.count() > 0)
//    {
//        player->stop();
//        QVariant variant = items[0]->data(Qt::UserRole); // 获取用户数据
//        Song* song = variant.value<Song*>();

//        ui->playlist_widget->hide();
//        addPlaylist(cur_music_list);
//        Song* s = playlist_hash[song];
//        playlist->setCurSong(s);

//        playSong(s);
//    }
//}

//数字时间转为字符时间
QString Widget::getTime2Str(int time)
{
    if(time < 0)
        return "00:00";
    int h,m,s;
    time /= 1000;  //获得的时间是以毫秒为单位的
    //h = time/3600;
    m = time/60;
    s = time-m*60;
    int len = 0;
    int tmp = m;
    while(tmp)
    {
        tmp /= 10;
        len += 1;
    }
    len = len >= 2? len : 2;
    return QString("%1:%2").arg(m,len,10,QLatin1Char('0')).arg(s,2,10,QLatin1Char('0'));
}

//根据当前播放进度设置播放时间
void Widget::setPlayTime()
{
    ui->cur_music_time->setText(getTime2Str(player->position()));
}

//设置当前播放时间，单位：毫秒
void Widget::setPlayTime(int time)
{
    ui->cur_music_time->setText(getTime2Str(time));
}

//从头播放歌曲
void Widget::playSong(Song* song)
{
    //基础信息显示
    song->readPic();
    ui->name_label->setText(song->Name.size() > 0? song->Name : song->File_name);
    ui->singer_label->setText(song->Singer);

    //设置播放路径
    player->stop();
    player->setMedia(QUrl::fromLocalFile(song->Url));

    //设置歌词
    song->printInfo();
    ui->songname_lw->setText(song->Name.size() > 0? song->Name : song->File_name);
    ui->singer_lw->setText("歌手：" + song->Singer);
    ui->album_lw->setText("专辑：" + song->Album);
    qDebug() << "图片地址：" << song->Picture_url;
    if(song->Picture_url.size() != 0)
    {
        qDebug() << "load picture";
        ui->album->setStyleSheet("border-image:url(" + song->Picture_url + ")");
        ui->picture_lw->setStyleSheet("border-image:url(" + song->Picture_url + ")");
    }
    else
    {
        ui->album->setStyleSheet("border-image:url(:/resource/default_album.svg)");
        ui->picture_lw->setStyleSheet("border-image:url(:/resource/default_album.svg)");
    }

    loadLyrics("E:\\CloudMusic\\test\\lyrics\\" + song->File_name + ".lrc");

    // 播放音乐，设置定时器
    ui->play_ctl_slider->setValue(player->position());
    ui->play_btn->setIcon(QIcon(":/resource/pause.svg"));

    player->play();
    playslider_timer->start();

    if(lyrics_info.size > 0)
    {
        last_time = lyrics_info.getListLyricsTime().at(0);
        lyrics_timer->start(last_time);
    }
}

//加载歌词并显示
void Widget::loadLyrics(QString FileName)
{
    cur_lyrics_line = 0;
    if(FileName != NULL)
    {
        if(lyrics_info.readLyricsFile(FileName) && lyrics_info.size > 0)
        {
            int pre_size = lyrics.size();

            for(int i = 0; i < lyrics_info.list_lyrics_text.size(); i++)
            {
                if(i < pre_size)
                {
                    lyrics[i] = new QListWidgetItem();
                    lyrics[i]->setText(lyrics_info.list_lyrics_text.at(i));
                    lyrics[i]->setFont(font_normal);
                    ui->lyrics_listwidget->addItem(lyrics[i]);
                }
                else
                {
                    QListWidgetItem* tmp = new QListWidgetItem();
                    tmp->setText(lyrics_info.list_lyrics_text.at(i));
                    tmp->setFont(font_normal);
                    lyrics.push_back(tmp);
                    ui->lyrics_listwidget->addItem(lyrics[i]);
                }
            }

            return;
        }
        else
        {
            showNoLyrics();
        }
    }
    else
        showNoLyrics();
}

//无歌词的显示
void Widget::showNoLyrics()
{
    qDebug() << "歌词行数:" << lyrics.size();
    if(lyrics.size() > 0)
    {
        //qDebug() << lyrics[0]->text();
        //会把QListwidgetItem的对象也delete掉
        ui->lyrics_listwidget->clear();
        //qDebug() << lyrics[0]->text();
    }
    else
        ui->lyrics_listwidget->clear();
}

//歌词面板定时器的执行函数
void Widget::showNextLyrics()
{
    if(lyrics_info.size == 0)
        return;

    if(cur_lyrics_line > 0)
    {
        lyrics[cur_lyrics_line - 1]->setFont(font_normal);
    }
    lyrics[cur_lyrics_line]->setFont(font_bold);
    ui->lyrics_listwidget->scrollToItem(lyrics[cur_lyrics_line], QAbstractItemView::PositionAtCenter);
    cur_lyrics_line += 1;

    if(cur_lyrics_line < lyrics_info.list_lyrics_time.size() && QMediaPlayer::PlayingState == player->state())
    {
        lyrics_timer->start(lyrics_info.list_lyrics_time[cur_lyrics_line] - last_time);
        last_time = lyrics_info.getListLyricsTime().at(cur_lyrics_line);
    }
}

//根据时间确定歌词位置
void Widget::setLyricsPos(int time)
{
    if(lyrics_info.size == 0)
        return;

    int pos = getTargetPos(lyrics_info.list_lyrics_time, time);

    if(pos != - 1)
    {
        ui->lyrics_listwidget->scrollToItem(lyrics[pos], QAbstractItemView::PositionAtCenter);
        lyrics[cur_lyrics_line - 1]->setFont(font_normal);
        lyrics[pos]->setFont(font_bold);
    }

    cur_lyrics_line = pos + 1;

    if(pos != lyrics.size() - 1 && QMediaPlayer::PlayingState == player->state())
    {
        lyrics_timer->start(lyrics_info.list_lyrics_time[cur_lyrics_line] - time);
    }

    last_time = lyrics_info.list_lyrics_time[cur_lyrics_line];
}

//显示\关闭歌词面板
void Widget::showLyricWidget()
{
    //qDebug() << ui->lyric_widget->visibleRegion();
    if(ui->lyrics_widget->visibleRegion().isNull())
    {
        qDebug() << "显示歌词";
        ui->lyrics_widget->show();
    }
    else
    {
        qDebug() << "关闭歌词";
        ui->lyrics_widget->hide();
    }
}

//显示\关闭播放列表
void Widget::showPlaylistWidget()
{
    if(ui->playlist_widget->visibleRegion().isNull())
    {
        qDebug() << "显示播放列表";
        ui->playlist_widget->show();
    }
    else
    {
        qDebug() << "关闭播放列表";
        ui->playlist_widget->hide();
    }
}

void Widget::addPlaylist(MusicList *ml)
{
    //清空原来的内容
    ui->playlist_tabel->clearContents();
    playlist_hash.clear();
    playlist->clear();

    //添加歌单到播放列表，这里是复制，所以暂不考虑重复添加
    Song* tmp_song = ml->Start();
    while(tmp_song != nullptr)
    {
        Song* s = tmp_song->copy();
        playlist->addSong(s);
        playlist_hash[tmp_song] = s;
        tmp_song = ml->next();
    }

    ListNode<Song*>* dump = playlist->getDump();
    ListNode<Song*>* tmp_node = dump->next;

    ui->playlist_tabel->setRowCount(playlist->getSize());

    for(int i = 0; i < playlist->getSize(); i++)
    {
        Song* tmp_song = tmp_node->data;
        QTableWidgetItem *item1 = new QTableWidgetItem (tmp_song->Name.size() > 0? tmp_song->Name : tmp_song->File_name);
        item1->setData(Qt::UserRole, QVariant::fromValue(tmp_song));
        ui->playlist_tabel->setItem(i, 0, item1);

        QTableWidgetItem *item2 = new QTableWidgetItem (tmp_song->Singer);
        ui->playlist_tabel->setItem(i, 1, item2);

        QTableWidgetItem *item3 = new QTableWidgetItem (tmp_song->Album);
        ui->playlist_tabel->setItem(i, 2, item3);
        tmp_node = tmp_node->next;
    }

    ui->playlist_num->setText(QString("共%1首").arg(playlist->getSize()));
}

//重写鼠标按下事件
void Widget::mousePressEvent(QMouseEvent *event)
{
    mMoveing = true;
    //记录下鼠标相对于窗口的位置
    //event->globalPos()鼠标按下时，鼠标相对于整个屏幕位置
    //pos() this->pos()鼠标按下时，窗口相对于整个屏幕位置
    mMovePosition = event->globalPos() - pos();
    return QWidget::mousePressEvent(event);
}

//重写鼠标移动事件
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    //(event->buttons() && Qt::LeftButton)按下是左键
    //鼠标移动事件需要移动窗口，窗口移动到哪里呢？就是要获取鼠标移动中，窗口在整个屏幕的坐标，然后move到这个坐标，怎么获取坐标？
    //通过事件event->globalPos()知道鼠标坐标，鼠标坐标减去鼠标相对于窗口位置，就是窗口在整个屏幕的坐标
    if (mMoveing && (event->buttons() && Qt::LeftButton)
        && (event->globalPos()-mMovePosition).manhattanLength() > QApplication::startDragDistance())
    {
        move(event->globalPos()-mMovePosition);
        mMovePosition = event->globalPos() - pos();
    }
    return QWidget::mouseMoveEvent(event);
}

//重写鼠标释放事件
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    mMoveing = false;
}

//处理自定义信号，这里主要处理点击进度条时发出的自定义信号，该信号用于完成一次性将滑块移动到点击位置的动作
bool Widget::event(QEvent *event)
{
    if (event->type() == SliderClickedEvent::eventType() && !isSliderMoved)
    {
        isSliderPressed = true;
        qDebug() << "MyEvent";

        if(player->duration() == 0)
        {
            ui->play_ctl_slider->setValue(0);
        }
        else
        {
            //停止进度条的定时器，设置进度条位置，再根据播放状态是否开启定时器
            playslider_timer->stop();
            int time = player->duration()*ui->play_ctl_slider->value()/1000;

            setLyricsPos(time);
            player->setPosition(time);
            setPlayTime(time);

            if(QMediaPlayer::PlayingState == player->state())
                playslider_timer->start();
        }

        isSliderPressed = false;
        return true;
    }

    return QWidget::event(event);
}

//加载QSS，自定义程序显示风格
void Widget::initUI()
{
    ui->close_btn->setProperty("class", "btn_tp");
    ui->min_btn->setProperty("class", "btn_tp");
    ui->max_btn->setProperty("class", "btn_tp");
    ui->icon_btn->setProperty("class", "btn_tp");
    ui->collect_btn->setProperty("class", "btn_tp");
    ui->favorite_btn->setProperty("class", "btn_tp");
    ui->playlist_btn->setProperty("class", "btn_tp");
    ui->add_song->setProperty("class", "btn_tp");
    ui->playmode_btn->setProperty("class", "btn_tp");


    ui->play_btn->setProperty("class", "btn_tp");
    ui->next_btn->setProperty("class", "btn_tp");
    ui->pre_btn->setProperty("class", "btn_tp");
    ui->sound_btn->setProperty("class", "btn_tp");

    ui->add_music->setProperty("class", "btn_tp");

    ui->album->setProperty("class", "btn_tp radium");

    ui->top_widget->setProperty("class", "black_widget");
    ui->bottom_widget->setProperty("class", "black_widget");
    ui->show_widget->setProperty("class", "show_widget");

    ui->lyrics_widget->setProperty("class", "show_widget");

    ui->left_widget->setProperty("class", "show_widget right_border");
    ui->music_list_table->setProperty("class", "show_widget");
    ui->musiclist_listWidget->setProperty("class", "show_widget");

    ui->music_label->setProperty("class", "music_label");
    ui->singer_label->setProperty("class", "singer");
    ui->name_label->setProperty("class", "song_name");
    ui->playmode_label->setProperty("class", "playmode_label");

    ui->singer_lw->setProperty("class", "singer_lw");
    ui->album_lw->setProperty("class", "singer_lw");
    ui->songname_lw->setProperty("class", "song_name_lw");

    ui->cur_music_time->setProperty("class", "singer center");
    ui->total_music_time->setProperty("class", "singer center");

    ui->album->setStyleSheet("border-image:url(resource/default_album.svg)");
    ui->picture_lw->setStyleSheet("border-image:url(resource/default_album.svg)");

    ui->playlist_widget->setProperty("class", "playlist_widget");
    ui->playlist_label->setProperty("class", "playlist_name");
    ui->playlist_tabel->setProperty("class", "playlist_table");
    ui->playlist_num->setProperty("class", "playlist_num");


    QFile file(":/main.qss");
    if(file.open(QFile::ReadOnly))
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        file.close();
    }
    else
        qDebug("Open QSS file failed.");
}
